#include "stdafx.h"
#include <d3dx9.h>
#include "shaderproc.h"
#include "common.h"

#include <vector>



int CleanShader(const DWORD *in, DWORD *out) {
	DWORD *orig_out = out;
	DWORD value;
	do {
		value = *in;
		if ((value & 0xFFFF) == 0xFFFE) {
			printf("Stripped %i-byte comment\n", value>>14);
			//MessageBox(0,"Comment detected",0,0);
			in++;
			in += value >> 16;
			continue;
		} else {
			*out = value;
			out++;
			in++;
		}
	} while (value != 0x0000FFFF);
	return (out - orig_out) * 4;
}


int ProcessShader(const char *filename, const char *entry, unsigned char *output, bool pixel)
{
	int sz;
	LPD3DXBUFFER pCode, pErrors;
	if (FAILED(D3DXCompileShaderFromFile(
                                filename,
                                NULL, NULL,
                                entry,
								pixel ? "ps_3_0" : "vs_3_0",
                                D3DXSHADER_OPTIMIZATION_LEVEL3,
                                &pCode,
                                &pErrors,
                                NULL
                            )))
	{
		printf("%s", (char*)pErrors->GetBufferPointer());
		pErrors->Release();
		sz=0;
		errorcount++;
	}
	else
	{
		// TODO: Try cutting the last 48 bytes. It's just a copyright.
		sz = pCode->GetBufferSize();
		//memcpy(output, pCode->GetBufferPointer(), sz);
		sz = CleanShader((const DWORD *)pCode->GetBufferPointer(), (DWORD *)output);
		pCode->Release();
	}

	return sz;
}